import { createContext, FC, useContext, useState,React } from "react";

// ====== 1. define provider context type
type CounterProviderContextType = {
    count: number;
    add: () => void;
    minus: () => void;
};

// ======= 2.define provider context
interface CounterContextProviderProps {
    children: React.ReactNode
};

// ======= 3. Create context data
const CounterContext = createContext<CounterProviderContextType>({
    count: 0,
    add: () => {},
    minus: () => {},
});
// ===== use useContext to seal

export default () => useContext(CounterContext);


// ======= 4.Create context provider.
export const CounterProvider: FC<CounterContextProviderProps> = ({ children }) => {
    const [count, setCount] = useState<number>(0);
    
    const add = () => {
        setCount(prevCount => prevCount + 1);
    };

    const minus = () => {
        if(count === 0) return;
        setCount(prevCount => prevCount - 1);
    };

    const counterContextValue = {
        count,
        add,
        minus,
    };

    // 通过 Provider 包裹子组件，将 context 传递给子组件
    // 子组件可以通过 useContext 来获取 context 的值
    return (
        <CounterContext.Provider value={counterContextValue}>
            {children}
        </CounterContext.Provider>
    );
};





/**
 * Summary:
 *  --- In Provider / Context hooks:
 *      Step_1: define XxxxContext interface
 *      Step_2: define XxxxProvider interface
 *      Step_3: Initialize XxxxContext by hook: createContext()
 *
 *      Step_4_0: Define XxxxProvider Component
 *      Step_4.1: Define XxxxProvider return type: FC<LeslieProviderProps>
 *      Step_4.2: extract {children} node in parameters
 *      Step_4.3: Complete biz logic
 *      Step_4.4: Define context value
 *      Step_4.5: Pass context value on Provider element
 *      Step_4.6: expose {children} inner Provider
 *
 *      Step_5: export default function: export default () => useContext(LeslieContext);

 *
 *  --- In Parent Component
 *      Step_6: Import Provider, then wrap Biz component in it.
 *
 *  --- In Child Component
 *      Step_7: Import default function: import useLeslie from "./useLeslie";
 *      Step_8: extract context value const {xx,setXx} = useLeslie()
 *
 *  --- Done
 *
 */